package core.network.client2game.handler.ddz;

import java.io.IOException;

import business.ddz.c2s.cclass.DDZ_define;
import business.ddz.c2s.iclass.CDDZ_OpenStartGame;
import business.ddz.c2s.iclass.SDDZ_OpenStartGame;
import business.global.pk.ddz.DDZRoom;
import business.global.pk.ddz.DDZRoomPos;
import business.global.pk.ddz.DDZRoomSet;
import com.ddm.server.websocket.def.ErrorCode;
import com.ddm.server.websocket.exception.WSException;
import com.ddm.server.websocket.handler.requset.WebSocketRequest;
import com.google.gson.Gson;

import business.global.room.RoomMgr;
import business.player.Player;
import core.network.client2game.handler.PlayerHandler;
import core.network.http.proto.SData_Result;

/**
 * 明牌开始
 * */

public class CDDZOpenStartGame extends PlayerHandler{

	@SuppressWarnings("rawtypes")
	@Override
	public void handle(Player player, WebSocketRequest request, String message) throws WSException, IOException {
		final CDDZ_OpenStartGame clientPack = new Gson().fromJson(message, CDDZ_OpenStartGame.class);
    	
		DDZRoom room = (DDZRoom) RoomMgr.getInstance().getRoom(clientPack.roomID);
    	
    	DDZRoomPos pos = (DDZRoomPos) room.getRoomPosMgr().getPosByPid(player.getPid());
    	if (null ==  pos ) {
    		request.error(ErrorCode.NotAllow, "CDDZOpenStartGame not find player roomID:"+clientPack.roomID+",playerid = "+player.getPid());
    		return;
		}
		if(!room.isCanOpenCard()){
			request.error(ErrorCode.NotAllow,"!room.isCanOpenCard():"+ !room.isCanOpenCard());
			return;
		}
    	if (clientPack.isContinue) {
        	SData_Result result = room.continueGame(player.getPid());
        	if (ErrorCode.Success.equals(result.getCode())) {
				pos.setOpenCardStartGame(1);
				room.setFirstStartOpenPos(pos.getPosID(),false);
				room.getRoomPosMgr().notify2All(SDDZ_OpenStartGame.make(room.getRoomID(), pos.getPosID(), true));
				request.response();
			} else {
        		request.error(result.getCode(), result.getMsg());
        	}
		} else {
    		if(clientPack.openCard!=1&&clientPack.openCard!=0){
				request.error(ErrorCode.NotAllow,"clientPack.openCard is error"+clientPack.openCard);
				return;
			}
			if(pos.getOpenCardStartGame()!=-1){
				request.error(ErrorCode.NotAllow,"has show"+pos.getOpenCardStartGame());
				return;
			}
			pos.setOpenCardStartGame(clientPack.openCard);
			if(clientPack.openCard==1){
				room.setFirstStartOpenPos(pos.getPosID(),false);
			}
			boolean isAllShow = room.getRoomPosMgr().getPosList().stream().allMatch(n->((DDZRoomPos)n).getOpenCardStartGame()!=-1);
			if(isAllShow){
				((DDZRoomSet)room.getCurSet()).startSet();
				((DDZRoomSet)room.getCurSet()).onChangeStatus(DDZ_define.DDZ_GameStatus.DDZ_GAME_STATUS_SENDCARD);
			}
			room.getRoomPosMgr().notify2All(SDDZ_OpenStartGame.make(room.getRoomID(), pos.getPosID(), clientPack.openCard==1));
			request.response();
		}
	}
}
